package com.itheima.test8;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/*
下载 小说  服务端
 */
public class ServerTest {
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(10002);
        while (true) {
            final Socket accept = ss.accept();
            InetAddress ip = accept.getInetAddress();
            String hostAddress = ip.getHostAddress();
            String hostName = ip.getHostName();
            System.out.println("ip:"+hostAddress+";;主机名为"+hostName+";;正在下载");
            new Thread(() -> {
                BufferedInputStream bis = null;
                try {
                    bis = new BufferedInputStream(new FileInputStream("day13\\copy\\dldl.txt"));
                    OutputStream os = accept.getOutputStream();
                    BufferedOutputStream bos = new BufferedOutputStream(os);
                    byte[] bytes = new byte[1024];
                    int len;
                    while ((len = bis.read(bytes)) != -1) {
                        bos.write(bytes, 0, len);
                    }
                    bos.flush();
                    accept.shutdownOutput();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("ip:"+hostAddress+";;主机名为"+hostName+";;下载完毕");
                        try {
                            accept.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                }
            }).start();
        }
    }
}
